<?php

namespace app\admin\controller;

use think\exception\ValidateException;
use app\model\CustomerField;

class CustomerfieldController extends Base
{

	function index()
	{
		$keyword = input('post.keyword', '', 'serach_in');
		$query = CustomerField::where(['weid' => weid()]);
		if (!empty($keyword)) {
			$query->where('viewmingcheng', 'like', '%' . $keyword . '%');
		}
		
		$Fielddata = $query->order('sort asc,id asc')->select()->toArray();

		if (empty($Fielddata)) {
			CustomerField::datainitial();
			$Fielddata = $query->order('sort asc,id asc')->select()->toArray();
		}

		$data['data'] = $Fielddata;
		return $this->json($data);
	}

	function updateExt()
	{
		$postField = 'id,status,is_listView,is_import,is_search,sort';
		$data = $this->request->only(explode(',', $postField), 'post', null);
		if (!$data['id']) throw new ValidateException('参数错误');
		CustomerField::update($data);

		return $this->json(['msg' => '操作成功']);
	}

	public function add()
	{
		$postField = 'fieldsmingcheng,viewmingcheng,is_listView,is_search,is_import,inputtype,selectvalue,defaultvalue,shuoming,status,sort';
		$data = $this->request->only(explode(',', $postField), 'post', null);
		$data['weid'] = weid();
		$data['selectvalue'] = implode(',', $data['selectvalue']);
		$data['create_time'] = time();
		$data['update_time'] = time();

		try {
			$res = CustomerField::create($data);
			if ($res->id && empty($data['sort'])) {
				CustomerField::update(['sort' => $res->id, 'id' => $res->id]);
			}
		} catch (\Exception $e) {
			throw new ValidateException($e->getMessage());
		}

		return $this->json(['msg' => '添加成功', 'data' => $res->id]);
	}

	public function update()
	{
		$id = $this->request->post('id');
		if (empty($id)) {
			return $this->add();
		} else {
			$postField = 'id,fieldsmingcheng,viewmingcheng,is_listView,is_search,is_import,inputtype,selectvalue,defaultvalue,shuoming,status,sort';
			$data = $this->request->only(explode(',', $postField), 'post', null);
			$data['selectvalue'] = implode(',', $data['selectvalue']);
			try {
				CustomerField::update($data);
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}
			return $this->json(['msg' => '修改成功']);
		}
	}

	function getUpdateInfo()
	{
		$id =  $this->request->post('id', '', 'serach_in');
		if (!$id) throw new ValidateException('参数错误');
		$data = CustomerField::field('*')->find($id)->toArray();
		$data['selectvalue'] = explode(',', $data['selectvalue']);

		return $this->json(['data' => $data]);
	}

	function delete()
	{
		$idx =  $this->request->post('id', '', 'serach_in');
		if (!$idx) throw new ValidateException('参数错误');
		CustomerField::destroy(['id' => explode(',', $idx)], true);
		return $this->json(['msg' => '操作成功']);
	}
}
